<?php defined('SYSPATH') or die('No direct access allowed.');

class Model_User extends ORM {

	/**
	 * Complete the login for a user by incrementing the logins and saving login timestamp
	 *
	 * @return void
	 */
	public function complete_login()
	{
		if ($this->_loaded) {
			// Update the number of logins
			$this->logins = new Database_Expression('logins + 1');

			// Set the last login date
			$this->last_login = time();

			// Save the user
			$this->update();
		}
	}
    
    /**
     * Добавление пользователя
     * 
     * @param   string   email
     * @param   string   password
     * @return  Model_User
     */
    public function add_user($email, $password, $balance = 50, $site = null, $utm_marks = null)
    {
        $email = trim($email);
        if (!$email) {
            throw new Model_Exception('E-mail должен быть задан');
        }
        if (!Valid::email($email)) {
            //throw new Model_Exception('E-mail некорректного формата'); 
        }
        
        $password = trim($password);
        if (!$password) {
            throw new Model_Exception('Пароль должен быть задан');
        }
        
        $this->email    = $email;
        $this->password = Model_Auth::instance()->hash_password($password);
        if ($site) {
            $this->site = $site;    
        }
        $this->balance_ready = $balance;
        if (isset($_COOKIE['recommend']) && $_COOKIE['recommend']) {
            $this->recommend_id = $_COOKIE['recommend'];    
        }
        if ($utm_marks) {
            $this->utm_marks = $utm_marks;    
        }
        $this->registration_date = time();
        $this->save();
        
        return $this;
    }
    
    /**
    * put your comment there...
    * 
    * @param mixed $email
    * @param mixed $password
    */
    public function edit_user($email, $password = null)
    {
        $this->email    = $email;
        if ($password) {
            $this->password = Model_Auth::instance()->hash_password($password);
        }   
        $this->save();
        
        return $this;
    }
    
    public static function generate_password($length = 10)
    {
        $arr = array('a','b','c','d','e','f',
                 'g','h','i','j','k','l',
                 'm','n','o','p','r','s',
                 't','u','v','x','y','z',
                 'A','B','C','D','E','F',
                 'G','H','I','J','K','L',
                 'M','N','O','P','R','S',
                 'T','U','V','X','Y','Z',
                 '1','2','3','4','5','6',
                 '7','8','9','0',
                 '(',')','[',']',);
                 
        // Генерируем пароль
        $pass = '';
        for ($i = 0; $i < $length; $i++) {
            // Вычисляем случайный индекс массива
            $index = rand(0, count($arr) - 1);
            $pass .= $arr[$index];
        }
        return $pass;
    }

}